<?php
namespace app\admin\controller;
use think\Db;
/**
 * #任务管理#{管理前台任务的配置信息开启功能}
 */
class Taskoptions extends Common{
    /**
     * #任务容器列表#
     * @param  string $group 分组ID
     * @param  string $type  状态
     * @return view
     */
    function index($group='-1',$type="-1"){
        $params=[
            'group'=>$group,
            'type'=>$type,
        ];
        $where=[];
        if($group>0){
            $where['group_id']=$group;
        }
        if($type>=0){
            $where['status']=$type;
        }
        $list=model($this->table)->readAll($where,true,['order'=>'sort,id']);
        foreach ($list as $k => $v) {
            if($v['options']){
                $list[$k]['options']=json_decode($v['options'],true);
            }else{
                $list[$k]['options']=[];
            }
        }
        $list->appends($params);
        $this->assign('list',$list);
        $this->assign('params',$params);
        $groups=model('taskgroup')->readAll();
        $this->assign('groups',$groups);

        // 任务功能列表
        $funcs=model('taskfunc')->readAll(['status'=>1],0,['with'=>'taskparams']);
        $this->assign('funcs',$funcs);
        return view();
    }
    /**
     * 任务容器的上下移动
     * @param  array    $val [{id,sort}]
     * @return json
     */
    function record($val=[]){
        if(request()->isAjax()||request()->isPost()){
            if(empty($val)){
                $this->error('缺少数据');
            }
            $ids=[];
            
            foreach($val as $v) {
                if(!isset($v['id'])||$v['id']<=0||!isset($v['sort'])||$v['sort']<0){
                    $this->error('数据有误');
                }
                array_push($ids,$v['id']);
            }
            $where=[
                'id'=>['id','in',$ids],
            ];
            $nums=db($this->table)->where($where)->count();
            if($nums!==count($ids)){
                $this->error('数据有误');
            }
            $save=model($this->table)->edit($val);
            if(!$save){
                $this->error(lang('Failed operation'));
            }
            $this->success(lang('Successful operation'));
        }
    }
    /**
     * #为任务容器分配功能#
     * @param  integer $id      任务容器ID
     * @param  string  $options 功能属性
     * @param  string  $params 功能属性(简化版)
     * @return json
     */
    function grantFunc($id=0,$options='',$params=''){
        if(request()->isAjax()||request()->isPost()){
            if($id<=0){
                $this->error('该项不存在');
            }
            $has=model($this->table)->where(['id'=>$id])->count();
            if(!$has){
                $this->error('该项不存在');
            }
            if(is_array($options)){
                $options=json_encode($options);
            }
            if(is_array($params)){
                $params=json_encode($params);
            }
            $data=['id'=>$id,'params'=>$params];
            // 编辑功能属性使用
            if($options!=-1){
                $data['options']=$options;
            }
            $edit=model($this->table)->edit($data);
            if(is_null($edit)){
                $this->error(lang('Failed operation'));
            }   
            $this->success(lang('Successful operation'));
        }
    }
    /**
     * #新增、编辑任务容器#
     * @param integer $id [description]
     */
    function add($id=0){
        if(request()->isAjax()||request()->isPost()){
            if($id>0){
                $has=model($this->table)->where(['id'=>$id])->count();
                if(!$has){
                    $this->error('该项不存在');
                }
            }
            $data=[
                'title'=>input('title/s',''),
                'name'=>input('name/s',''),
                'icon'=>input('icon/s',''),
                'action'=>input('action/d',0),
                'status'=>input('status/d',1),
                'group_id'=>input('group_id/d',0),
                'type'=>input('type/d',1),
                'pc'=>input('pc/d',1),
                'phone'=>input('phone/d',1),
            ];
            $validate=$this->validate($data,[
                'title|标题'=>'require',
                'name|Name'=>'require',
                'action|Action'=>'require',
                'icon|图标'=>'require',
                'group_id|分组'=>'require',
            ]);
            if(true!==$validate){
                $this->error($validate);
            }
            // $hasName=model($this->table)->where(['name'=>$data['name'],'id'=>['id','<>',$id]])->count();
            // if($hasName){
            //     $this->error('请保证Name的唯一性');
            // }
            // $hasAction=model($this->table)->where(['group_id'=>$data['group_id'],'action'=>$data['action'],'id'=>['id','<>',$id]])->count();
            // if($hasAction){
            //     $this->error('该分组下已存在Action为‘'.$data['action'].'’的任务');
            // }
            $operation=null;
            if($id>0){
                $operation=model($this->table)->edit($data,['id'=>$id]);
            }else{
                $operation=model($this->table)->add($data);
            }
            if(is_null($operation)){
                $this->error(lang('Failed operation'));
            }   
            $this->success(lang('Successful operation'));
        }
    }
    /**
     * #禁用、启用任务容器#
     * @param  integer $id 任务容器ID
     * @param  array   $ids 任务容器ID组
     * @return json
     */
    function close($id=0){
        if(request()->isAjax()||request()->isPost()){
            $ids=input('ids/a',[]); // 多项
            if($id<=0&&empty($ids)){
                $this->error(lang('Data does not exist'));
            }
            $where="";
            if(!empty($ids)){
                $ids=implode(',', $ids);
                $where.=" `id` in ({$ids}) ";
            }else{
                $where.=" `id`={$id} ";
            }
            $rs=model($this->table)->close($where,'status',true);
            if($rs){
                $this->success(lang('Successful operation'));
                die;
            }
            $this->error(lang('Failed operation'));
        }
    }
    
    /**
     * #任务容器分组#
     * @return [type] [description]
     */
    function group(){
        $list=model('taskgroup')->readAll([],true);
        $this->assign('list',$list);
        return view();
    }
    /**
     * #添加、更改任务容器分组#
     * @return json
     */
    function groupAdd(){
        if(request()->isAjax()||request()->isPost()){
            $id=input('id/d',0);
            if($id>0){
                $has=model('taskgroup')->where(['id'=>$id])->count();
                if(!$has){
                    $this->error('该项不存在');
                }
            }
            $data=[
                'title'=>input('title/s',''),
                'event'=>input('event/s',''),
                'status'=>input('status/d',1),
                'pc'=>input('pc/d',1),
                'phone'=>input('phone/d',1),
                'remark'=>input('remark/s',''),
            ];
            $validate=$this->validate($data,[
                'title|标题'=>'require',
                'event|Event'=>'require',
            ]);
            if(true!==$validate){
                $this->error($validate);
            }
            $hasEvent=model('taskgroup')->where(['event'=>$data['event'],'id'=>['id','<>',$id]])->count();
            if($hasEvent){
                $this->error('请保证Event的唯一性');
            }
            $operation=null;
            if($id>0){
                $operation=model('taskgroup')->edit($data,['id'=>$id]);
            }else{
                $operation=model('taskgroup')->add($data);
            }
            if(is_null($operation)){
                $this->error(lang('Failed operation'));
            }   
            $this->success(lang('Successful operation'));
        }
    }
    /**
     * #任务容器功能#
     * @return view
     */
    function func(){
        $list=model('taskfunc')->readAll([],true,['with'=>'taskparams']);
        $this->assign('list',$list);
        $params=model('taskparams')->readAll(['status'=>1]);
        $this->assign('params',$params);
        return view();
    }
    /**
     * #新增、更新任务容器功能#
     * @return json
     */
    function funcAdd(){
        if(request()->isAjax()||request()->isPost()){
            $id=input('id/d',0);
            if($id>0){
                $has=model('taskfunc')->where(['id'=>$id])->count();
                if(!$has){
                    $this->error('该项不存在');
                }
            }
            $data=[
                'key'=>input('key/s',''),
                'remark'=>input('remark/s',''),
                'status'=>input('status/d',1),
                'is_default'=>input('is_default/d',0),
            ];
            $validate=$this->validate($data,[
                'key|键名'=>'require',
                'remark|功能说明'=>'require',
            ]);
            if(true!==$validate){
                $this->error($validate);
            }
            $hasKey=model('taskfunc')->where(['key'=>$data['key'],'id'=>['id','<>',$id]])->count();
            if($hasKey){
                $this->error('请保证Key的唯一性');
            }
            $operation=null;
            if($id>0){
                $operation=model('taskfunc')->edit($data,['id'=>$id]);
            }else{
                $operation=model('taskfunc')->add($data);
            }
            if(is_null($operation)){
                $this->error(lang('Failed operation'));
            }   
            $this->success(lang('Successful operation'));
        }
    }
    
    /**
     * #功能属性#
     * @return view
     */
    function params(){
        $list=model('taskparams')->readAll([],true);
        $this->assign('list',$list);
        return view();
    }
    /**
     * 获取当前任务容器功能的属性
     * @param  integer $id 任务功能ID
     * @return json
     */
    function getParamsIds($id=0){
        if(request()->isAjax()||request()->isPost()){
            $ids=model('taskfunc')->getParamsIds($id);
            $this->success(lang('Successful operation'),'',$ids);
        }
    }
    /**
     * #分配属性#{给每一个功能分配不同的属性}
     * @param  array  $diff 发生变化的属性ID组
     * @param  integer  $func_id 功能ID
     * @return json
     */
    function grantParams($diff=[],$func_id=0){
        if(request()->isAjax()||request()->isPost){
            if(empty($diff)||$func_id<=0){
                $this->error(lang('Data does not exist'));
            }
            $has=model('taskfunc')->read(['id'=>$func_id],'id');
            if(!count($has)){
                $this->error('不存在该角色');
            }
            $isRemove=model('func_pamams')->where(['func_id'=>$func_id,'params_id'=>$diff[0]])->count();
            if($isRemove){
                $where=[
                    'func_id'=>$func_id,
                    'params_id'=>['params_id','in',$diff]
                ];
                $del=model('func_pamams')->del($where);
                if($del){
                    $this->success('移除成功');
                    die;
                }
                $this->error('移除失败');
            }else{
                $data=[];
                foreach($diff as $v) {
                    $data[]=['func_id'=>$func_id,'params_id'=>$v];
                }
                $add=model('func_pamams')->add($data);
                if(count($add)){
                    $this->success('添加成功');
                    die;
                }
                $this->error('添加失败');
                
            }
        }
    }
    /**
     * #新增、更新功能属性#
     * @return json
     */
    function paramsAdd(){
        if(request()->isAjax()||request()->isPost()){
            $id=input('id/d',0);
            if($id>0){
                $has=model('taskparams')->where(['id'=>$id])->count();
                if(!$has){
                    $this->error('该项不存在');
                }
            }
            $data=[
                'key'=>input('key/s',''),
                'remark'=>input('remark/s',''),
                'status'=>input('status/d',1),
                'is_default'=>input('is_default/d',0),
                'value'=>input('value/s',''),
                'option'=>input('option/s',''),
            ];
            $validate=$this->validate($data,[
                'key|属性键名'=>'require',
                'remark|属性说明'=>'require',
            ]);
            if(true!==$validate){
                $this->error($validate);
            }
            $hasKey=model('taskparams')->where(['key'=>$data['key'],'id'=>['id','<>',$id]])->count();
            if($hasKey){
                $this->error('请保证Key的唯一性');
            }
            $operation=null;
            if($id>0){
                $operation=model('taskparams')->edit($data,['id'=>$id]);
            }else{
                $operation=model('taskparams')->add($data);
            }
            if(is_null($operation)){
                $this->error(lang('Failed operation'));
            }   
            $this->success(lang('Successful operation'));
        }
    }
}